package com.hy.admin.security.config;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.ast.And;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;


@Configuration
@EnableResourceServer
@Order(3)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter{

	@Autowired
    private CustomAccessDeniedHandler customAccessDeniedHandler;
	
	@Value("${authorize.urls}")
	private String urls;
	
	@Override
	public void configure(HttpSecurity http) throws Exception {
		http.requestMatchers().antMatchers("/api/**");
		if(StringUtils.isNotBlank(urls)) {
//			System.out.println(urls);
			String[] split = StringUtils.split(urls,",");
			for(String str:split) {
				http
				.authorizeRequests()
				.antMatchers(str)
				.permitAll();
			}
		}
		
			http.authorizeRequests()
			.antMatchers("/page/**","/api/**")
			.authenticated();
	}
	
	@Override
	public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
		resources
		.authenticationEntryPoint(new AuthExceptionEntryPoint())
        .accessDeniedHandler(customAccessDeniedHandler)
		.resourceId("mobile-resource")
		.stateless(true);
	}
	
}
